//
//  HHugeAnimationManger.m
//  linktuIOS
//
//  Created by hejunsong on 17/1/21.
//  Copyright © 2017年 tianxie. All rights reserved.
//

#import "HHugeAnimationManger.h"
@interface HHugeAnimationManger()<CAAnimationDelegate>
@property(nonatomic,strong) NSMutableArray *hugeAnimationArray;
@property(nonatomic,strong) UIImageView *imageView;

@end

static HHugeAnimationManger *hugemanger = nil;
@implementation HHugeAnimationManger

+(instancetype)hhugeAnimation
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hugemanger = [[HHugeAnimationManger alloc] init];
        hugemanger.hugeAnimationArray = [NSMutableArray array];
    });
    return hugemanger;
}


-(void)animationwithDict:(NSDictionary *)dict
{
    
    NSString *name = dict[@"name"];
    NSString *full = dict[@"full"];
    CGRect rect =   CGRectMake(0, 0, WIDTH, HEIGHT);
    if([full isEqualToString:@"no"])
    {
        rect = CGRectMake(WIDTH - 100 - 10, HEIGHT - 100 - 50, 100, 100);
    }
    
    NSString * filePath = [NSString stringWithFormat:@"%@/%@", cachePath, name];
    NSFileManager * manager = [NSFileManager defaultManager];
    NSArray * subPaths =    [manager subpathsAtPath:filePath];
    if(subPaths.count == 0)
    {
        return;
    }
    //存放图片的数组
    NSMutableArray * imageArray = [NSMutableArray array];
    for (int i = 1; i < subPaths.count; i++) {
        NSString * imageFile = [NSString stringWithFormat:@"%@/%@_%d.png", filePath, name,i];
        NSLog(@"imagefile ==  %@", imageFile);
        UIImage * image = [UIImage imageWithContentsOfFile:imageFile];
        CGImageRef cgimg = image.CGImage;
        [imageArray addObject:(__bridge UIImage *)cgimg];
    }
    _imageView = [[UIImageView alloc] initWithFrame:rect];
    [self.presentView insertSubview:_imageView atIndex:0];
    //创建CAKeyframeAnimation
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"contents"];
    animation.duration = 3.5;
    animation.delegate = self;
    
    animation.values = imageArray;
    [_imageView.layer addAnimation:animation forKey:nil];
    
}

-(void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag {
    [self.imageView removeFromSuperview];
    self.imageView = nil;
    
    [self.hugeAnimationArray removeObjectAtIndex:0];
    if(self.hugeAnimationArray.count > 0)
    {
        NSDictionary *dict = self.hugeAnimationArray.firstObject;
        [self animationwithDict:dict];
        
    }
    
}

-(void)addAnimationWithName:(NSString *)name isFull:(BOOL)full
{
    NSDictionary *dict = nil;
    if(full)
    {
        dict = @{@"name":name,@"full":@"yes"};
    }else
    {
        dict = @{@"name":name,@"full":@"no"};
    }
    
    if(self.hugeAnimationArray.count == 0)
    {
        [self.hugeAnimationArray addObject:dict];
        [self animationwithDict:dict];
    }else
    {
        [self.hugeAnimationArray addObject:dict];
    }
}




@end
